package com.knife.hospital.service.user;

import com.knife.hospital.config.BaseException;
import com.knife.hospital.constant.ResponseCode;

import com.knife.hospital.entity.UserPO;
import com.knife.hospital.entity.CommonUserPO;

import com.knife.hospital.mapper.UserPOMapper;
import com.knife.hospital.mapper.CommonUserPOMapper;

import com.knife.hospital.model.user.UserRegisterResponse;
import com.knife.hospital.model.user.UserRegisterRequest;

import com.knife.hospital.util.user.UserRegisterUtil;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.List;

/**
 * @author Zhenghao Ji
 */
@Service
public class UserRegisterServiceImpl implements UserRegisterService {
    @Resource
    private UserPOMapper userPOMapper;
    @Resource
    private CommonUserPOMapper commonUserPOMapper;
    @Resource
    private UserRegisterUtil userRegisterUtil;

    public UserRegisterResponse userRegisterFunction(UserRegisterRequest userRegisterRequest) {
        try {
            List<UserPO> userPOs = userPOMapper.selectByNickname(userRegisterRequest.getNickname());
            List<CommonUserPO> commonUserPOs = commonUserPOMapper.selectByName(userRegisterRequest.getNickname());
            if (userPOs.size() == 0) {
                UserPO userPOInsert = userRegisterUtil.UserRegisterRequestToUserPo(userRegisterRequest);
                userPOMapper.insertSelective(userPOInsert);
                CommonUserPO commonUserPO = userRegisterUtil.UserRegisterRequestToCommonUserPo(userRegisterRequest);
                userPOInsert = userPOMapper.selectByNickname(userRegisterRequest.getNickname()).get(0);
                commonUserPO.setId(userPOInsert.getId());
                commonUserPOMapper.insertSelective(commonUserPO);
                UserRegisterResponse userRegisterResponse = userRegisterUtil.userPoToUserResponse(userPOInsert);
                return userRegisterResponse;
            }
            else if (userPOs.size() == 1 && commonUserPOs.size() == 0) {
                CommonUserPO commonUserPO = userRegisterUtil.UserRegisterRequestToCommonUserPo(userRegisterRequest);
                UserPO userPOInsert = userPOMapper.selectByNickname(userRegisterRequest.getNickname()).get(0);
                commonUserPO.setId(userPOInsert.getId());
                commonUserPOMapper.insertSelective(commonUserPO);
                UserRegisterResponse userRegisterResponse = userRegisterUtil.userPoToUserResponse(userPOInsert);
                return userRegisterResponse;
            }
            else{
                throw new BaseException(ResponseCode.USER_OCCUPIED);
            }
        } catch (Exception e) {
            throw e;
        }
    }
}
